package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-21
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void addSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有课程分类
     *  总结：
     *      1、几层课程分类，那么就要几层遍历，如二层课程分类，那么就要遍历两次
     *      2、第一次遍历是封装一级分类
     *      3、第二次遍历是封装二级分类到一级分类
     *      4、依次类推
     * @return
     */
    @Override
    public List<OneSubject> getAllSubject() {
        //获取一级分类
        QueryWrapper<EduSubject> oneWrapper=new QueryWrapper<>();
        oneWrapper.eq("parent_id","0");
        List<EduSubject> oneSubjects = baseMapper.selectList(oneWrapper);
        //获取二级分类
        QueryWrapper<EduSubject> twoWrapper=new QueryWrapper<>();
        twoWrapper.ne("parent_id","0");
        List<EduSubject> twoSubjects = baseMapper.selectList(twoWrapper);
        //封装一级分类
        List<OneSubject> oneSubjectList=new ArrayList<>();
        for(int i=0;i<oneSubjects.size();i++){
            OneSubject oneSubject=new OneSubject();
            EduSubject eduSubject = oneSubjects.get(i);
            BeanUtils.copyProperties(eduSubject,oneSubject);
            oneSubjectList.add(oneSubject);
            //封装二级分类
            List<TwoSubject> twoSubjectList=new ArrayList<>();
            for(int j=0;j<twoSubjects.size();j++){
                if(twoSubjects.get(j).getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    EduSubject eduSubject1 = twoSubjects.get(j);
                    BeanUtils.copyProperties(eduSubject1,twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }
            //将二级二类的数据添加到一级分类中
            oneSubject.setChildren(twoSubjectList);
        }
        return oneSubjectList;
    }
}
